package com.wan.data.mysql.sql;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.wan.data.mysql.orm.meta.TableMeta;
import com.wan.util.SplitUtil;

import java.util.*;

public class EntitySql extends PreparedSql{
    private static final Log log = LogFactory.get();
    private final TableMeta tableMeta;
    /** 常用sql缓存 */
    private final Map<String,String> sqlCaches = new HashMap<>();

    public EntitySql(TableMeta tableMeta) {
        this.tableMeta = tableMeta;
        preload();
    }

    private void preload(){
        log.debug("#Entity SQL [{}] -----------",tableMeta.getEntityType().getCanonicalName());
        log.debug(selectById(1));
        log.debug(insertOne());
        log.debug(update());
        log.debug(delete(1));
    }

    /**
     * 根据id查询一条数据
     */
    public String selectById(int idLen) {
        return sqlCaches.computeIfAbsent(selectById + "_" + idLen,
                key-> String.format(selectById,tableMeta.getTableName(),tableMeta.getPkColumn().getColumnName(),getPlaceHolder(idLen)));
    }

    /**
     * 插入一条数据
     */
    public String insertOne(){
        return sqlCaches.computeIfAbsent(insertOne, sql->{
            String[] names = tableMeta.getOperateColumnNames(false);
            return String.format(sql,tableMeta.getTableName(),SplitUtil.concat(names),getPlaceHolder(names.length));
        });
    }

    /**
     * 修改一条数据
     */
    public String update(){
        return sqlCaches.computeIfAbsent(update, sql->{
            String[] names = tableMeta.getOperateColumnNames(false);
            return String.format(sql,tableMeta.getTableName(),getUpdateSets(names),tableMeta.getPkColumn().getColumnName());
        });
    }

    /**
     * 删除一条数据
     */
    public String delete(int idLen){
        return sqlCaches.computeIfAbsent(delete + "_" + idLen,
                key-> String.format(delete,tableMeta.getTableName(),tableMeta.getPkColumn().getColumnName(),getPlaceHolder(idLen)));
    }

    /**
     * 替换一条数据
     */
    public String replaceInto(){
        return sqlCaches.computeIfAbsent(replaceInto, sql->{
            String[] names = tableMeta.getOperateColumnNames(true);
            return String.format(sql,tableMeta.getTableName(),SplitUtil.concat(names),getPlaceHolder(names.length));
        });
    }

    /**
     * 根据条件查询
     */
    public String selectByCondition(String condition){
        String newSql = selectByCondition + condition;
        return sqlCaches.computeIfAbsent(newSql, sql-> String.format(sql,tableMeta.getTableName()));
    }

}
